package xt.outfood.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import xt.outfood.common.BaseContext;
import xt.outfood.common.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录拦截器配置(Filter过滤器的拦截)
 * @author 小小爱欧
 * @date 2022/7/20 9:24
 * 过滤器判断是否用户已经登录，否则跳转到登录页面，过滤器只能在web页面中，拦截器所有中都可用
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    /**
     * 路径匹配器的工具
     */
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获得请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);
        //定义不需要拦截处理的请求路径,无需登录就可以访问
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                //放行doc.html路径
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"

        };
        //判断本次请求是否需要处理
        boolean check = checkUrl(urls, requestURI);
        if (check) {
            log.info("不需要处理：",requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //判断员工登录状态，如果已经登录，直接放行（即session中是否含有employee的登录信息）
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，其ID为：{}",request.getSession().getAttribute("employee"));
            Long empId= (Long) request.getSession().getAttribute("employee");
            //存储本地session到ThreadLocal中
            BaseContext.setCurrentId(empId);
            long id = Thread.currentThread().getId();
            log.info("线程id为：{}",id);

            filterChain.doFilter(request, response);
            return;
        }
        //判断移动端用户登录状态（session中是否含有user信息，如果有，则直接放心）
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId!=null){
            log.info("用户已登录，id为：{}",userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //如果没有登录则返回未登录的结果
        log.info("用户未登录.........");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;

//        filterChain.doFilter(request, response);
    }

    /**
     * 路径匹配，检查本次路径中是否需要放行，利用AntPathMatcher路径匹配器工具
     *
     * @param urls
     * @param requestUrl
     * @return
     */
    public boolean checkUrl(String[] urls, String requestUrl) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
